﻿using System;
using TSharp.Core.Osgi.Internal;
using System.Collections.Generic;

namespace TSharp.Core.Osgi
{
    /// <summary>
    /// 
    /// </summary>
    /// <author>
    /// tangjingbo
    /// </author>
    /// <remarks>
    /// tangj15 at 2012-3-16 9:59
    /// </remarks>
    public interface IOsgiEventHandler : IAppHandler
    { 
        /// <summary>
        /// Completeds the specified engine.
        /// </summary>
        /// <param name="engine">The engine.</param>
        void Completed(OsgiEngine engine);
    }

    /// <summary>
    /// Osgi事件注册
    /// </summary>
    /// <author>
    /// tangjingbo
    /// </author> 
    public sealed class RegOsgiEventAttribute : RegExtensionAttribute
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="RegOsgiEventAttribute"/> class.
        /// </summary>
        /// <param name="evtType">Type of the evt.</param>
        public RegOsgiEventAttribute(Type evtType)
        {
            EventType = evtType;
        }

        internal Type EventType { get; private set; }
    }

    internal static class Ex
    {
        public static void Foreach<T>(this IEnumerable<T> es, Action<T> ac)
        {
            foreach (var oe in es)
                ac(oe);
        }
    }

    /// <summary>
    /// Osgi事件收集
    /// </summary>
    /// <author>
    /// tangjingbo
    /// </author>
    internal sealed class OsgiEventManager : ExtensionPoint<RegOsgiEventAttribute>
    {
        private static List<IOsgiEventHandler> evts = new List<IOsgiEventHandler>(50);

        public static IList<IOsgiEventHandler> Events
        {
            get { return evts.AsReadOnly(); }
        }

        internal override void EngineAdd(OsgiEngine.RegExtensionAttributeItem regAttribute)
        {
            var att = regAttribute.ExtensionAttribute as RegOsgiEventAttribute;
            if (att != null)
            {
                var constructorInfo = att.EventType.GetConstructor(new Type[0]);
                if (constructorInfo != null)
                {
                    var handler = constructorInfo.Invoke(new object[0]) as IOsgiEventHandler;
                    evts.Add(handler);
                }
            }
        }

        protected override void Register(System.Reflection.Assembly assembly, RegOsgiEventAttribute attribute)
        {
        }

        protected override void UnRegister(System.Reflection.Assembly assembly, RegOsgiEventAttribute attribute)
        {
        }
    }
}